package com.ml.rabbitmq.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 配置交换机和队列的绑定关系
 * 1、声明交换机
 * 2、声明队列
 * 3、将队列绑定到交换机上
 * @Author : zzy
 * @CreateTime : 2021-04-08
 **/
@Configuration
public class TTLRabbitConfig {

    //交换机
    @Bean
    public DirectExchange ttlDirectExchange() {
        return new DirectExchange("ttl_direct_exchange", true, false);
    }

    //队列
    @Bean
    public Queue ttlDirectQueue() {
        //设置队列过期时间
        Map<String, Object> args = new HashMap<>();
        //args.put("x-max-length", 5) 消息个数，超过这个值也会将消息放入死信队列中
        args.put("x-message-ttl", 5000);//ms  设定超时时间
        args.put("x-dead-letter-exchange", DeadRabbitConfig.DEAD_TTL_EXCHANGE);
        args.put("x-dead-letter-routing-key", DeadRabbitConfig.DEAD_TTL_ROUTING_KEY); //fanout模式的交换机不需要配此RoutingKey
        return new Queue("ttl.direct.queue", true, false, false, args);
    }

    //队列
    @Bean
    public Queue ttlMessageQueue() {
        return new Queue("ttl.message.direct.queue", true);
    }

    //绑定  将队列和交换机绑定
    @Bean
    public Binding bindingTtlDirectEmail(){
        return BindingBuilder.bind(ttlDirectQueue()).to(ttlDirectExchange()).with("ttl");
    }

    @Bean
    public Binding bindingTtlMessageEmail(){
        return BindingBuilder.bind(ttlMessageQueue()).to(ttlDirectExchange()).with("ttl-message");
    }

}
